// import Router from 'koa-router';
// import Koa from 'koa';
// import StaticServe from 'koa-static';

const Koa = require('koa');
const StaticServe = require('koa-static');
const Router = require('koa-router');
const HttpProxy = require('http-proxy');

const app = new Koa();
const router = new Router();
const main = StaticServe("G:\\导入-个人", { gzip: false });
const proxy = HttpProxy.createProxyServer({ ignorePath: true });

proxy.on('error', function (err, req, res) {
    res.writeHead(500, { 'Content-Type': 'text/plain' });
    res.end('代理请求出现异常');
    console.log(err);
});
proxy.on('proxyReq', function(proxyReq, req, res, options) {
    proxyReq.setHeader('User-Agent', 'Mozilla/5.0 (Linux; U; Android 2.2; en-us; Nexus One Build/FRF91) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1');
    proxyReq.setHeader('Host', '');
  });

router.get('/echo', ctx => {
    ctx.body = { path: __dirname };
});

const proxyMap = {
    mall: 'deposit.loan.mall.svc',
    admin: 'mall.admin.svc',
    mv2: 't.cn/RdEf2cL',     // 侏罗纪世界2
};
function getProxyUrl(originalUrl) {
    const key = originalUrl.split('/')[2];
    const svc = proxyMap[key];
    if (!svc) return false;
    let url = originalUrl.replace('/proxy/', '').replace(key, svc);
    if (!url.startsWith('http://')) {
        url = `http://${url}`;
    }
    console.log("| key=", key, " | svc=", svc, " | originalUrl=", originalUrl, " | url=", url);
    return url;
}

router.all('/proxy/*', ctx => {
    const url = getProxyUrl(ctx.originalUrl);
    if (!url) {
        ctx.throw(404);
        return;
    }
    ctx.respond = false;
    const { req, res } = ctx;
    proxy.web(req, res, { target: url, changeOrigin: true });
});

// 我不是药神（高清）
// http://t.cn/RdEcdoB

// 动物世界
// http://t.cn/RdEf2qd

// 侏罗纪世界2
// http://t.cn/RdEf2cL

// 猛虫过江
// http://t.cn/RdEf2fy

// 泄密者
// http://t.cn/RdEf2Mx

// 二龙湖爱情故事
// http://t.cn/RdEf2Jo

app.use(main);
app.use(router.routes());
app.listen(3000);
